package com.hs.jhzd.controller;

import com.hs.jhzd.entity.Police;
import com.hs.jhzd.entity.PoliceIntoPrisonRecord;
import com.hs.jhzd.entity.Prisoner;
import com.hs.jhzd.entity.User;
import com.hs.jhzd.entity.dto.LoginUser;
import com.hs.jhzd.repository.PoliceIntoPrisonRecordRepository;
import com.hs.jhzd.repository.PoliceRepository;
import com.hs.jhzd.repository.PrisonerRepository;
import com.hs.jhzd.repository.UserRepository;
import com.hs.jhzd.service.fp.FingerprintService;
import com.hs.jhzd.service.fp.jni.FingerprintZZJNIService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {

	@Autowired
	private PoliceRepository policeRepository;

	@Autowired
	private PrisonerRepository prisonerRepository;

	@Autowired
	private FingerprintService fingerprintService;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private PoliceIntoPrisonRecordRepository policeIntoPrisonRecordRepository;
	@Autowired
	private FingerprintZZJNIService fingerprintZZJNIService;

	@Value("${jsbh}")
	private String jsbh;

	@RequestMapping({ "/", "" })
	public Police login(String loginName, String password, String policeNum) {
		if (StringUtils.isNotBlank(policeNum)) {
			Police police = policeRepository.findByPoliceNum(policeNum);
			if (police == null) {
				throw new IllegalArgumentException("username or password error!");
			}
			return police;
		}

		Police police = null;
		if (police == null) {
			throw new IllegalArgumentException("username or password error!");
		}
		return police;
	}

	@RequestMapping({ "/userLogin" })
	public Police userLogin(String loginName, String password) {
		List<User> users = userRepository.findByPoliceNumAndRybj(loginName, 0);
		if (CollectionUtils.isEmpty(users)) {
			log.error("username【 {}】 not found!", loginName);
			return null;
		}
		User user = users.get(0);
		String pw = password + user.getSalt();
		if (!StringUtils.equals(user.getPwd(), getMD5(pw))) {
			log.error("password 【{}】 not equal db 【{}】", password, pw);
			return null;
		}
		Police police = null;
		if (StringUtils.isNumeric(loginName)) {
			log.info("normal user login 【{}】", loginName);
			police = policeRepository.findByPoliceNum(user.getPoliceNum());
			if (police != null) {
				user.setPolice(police);
			} else {
				log.error("police number 【{}】 not found!", loginName);
			}
		} else {
			log.info("admin user login 【{}】", loginName);
			police = new Police();
			police.setName(user.getName());
		//	police.setLoginName(loginName);
		}
		if (police != null) {
			police.setJsbh(jsbh);
		}
		return police;
	}

	public static String getMD5(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			return new BigInteger(1, md.digest()).toString(16);
		} catch (Exception e) {
			log.error("MD5加密出现错误", e);
		}
		return null;
	}

	@RequestMapping("/card")
	public LoginUser card(String jsbh, String jsh, String cardId) {
		LoginUser loginUser = new LoginUser();
		Prisoner prisoner = prisonerRepository.findByJshAndCardIdAndRybj(jsh, cardId, "3");
		if (prisoner != null) {
			loginUser.setCardId(prisoner.getCardId());
			loginUser.setPrisoner(prisoner);
			loginUser.setUserType(LoginUser.USER_TYPE_PRISONER);
			return loginUser;
		}

		Police police = policeRepository.findByCardId(cardId);
		if (police != null) {
			loginUser.setCardId(police.getCardId());
			loginUser.setPolice(police);
			loginUser.setUserType(LoginUser.USER_TYPE_POLICE);
			addPoliceIntoPrisonRecord(police, jsh);
			return loginUser;
		}

		return loginUser;
	}

	@RequestMapping("/fingerprintLogin")
	@ResponseBody
	public LoginUser fingerprintLogin(byte[] fingerprint, String jsbh, String jsh) {
		jsbh=this.jsbh;
		if (String.valueOf(fingerprint) == null || StringUtils.isBlank(jsbh) || StringUtils.isBlank(jsh)) {
			throw new IllegalArgumentException();
		}
		log.debug("尝试在押人员指纹比对 ...");
		LoginUser loginUser = prisonerFingerprintLogin(jsbh, jsh, fingerprint);
		if (loginUser != null && loginUser.getPrisoner() != null
				&& StringUtils.isNotBlank(loginUser.getPrisoner().getRybh())) {
			log.debug("在押人员指纹比对成功，人员编号： " + loginUser.getPrisoner().getRybh() + ",人员姓名："
					+ loginUser.getPrisoner().getName() + ",监舍号：" + loginUser.getPrisoner().getJsh());
		}
		if (loginUser == null || loginUser.getPrisoner() == null) {
			log.debug("尝试民警指纹比对 ...");
			loginUser = policeFingerprintLogin(jsbh, jsh, fingerprint);
			if (loginUser != null && loginUser.getPolice() != null) {
				addPoliceIntoPrisonRecord(loginUser.getPolice(), jsh);
			}
		}
		return loginUser;
	}

	public LoginUser prisonerFingerprintLogin(String prisonId, String dormCode, byte[] fingerprint) {

		LoginUser loginUser = new LoginUser();
		Prisoner prisoner = null;
		try {
			prisoner = fingerprintService.findPrisonerByFingerprint(fingerprint, dormCode, prisonId, "login");

		} catch (Exception ex) {
			log.error("登录失败", ex);
		}
		if (prisoner != null) {
			loginUser.setUserType(LoginUser.USER_TYPE_PRISONER);
			loginUser.setPrisoner(prisoner);
		}
		return loginUser;
	}

	/**
	 * 民警按指纹登录.
	 * 
	 * @param prisonId    检索编号
	 * @param dormCode    监舍号
	 * @param fingerprint 指纹数据
	 * @return 登录人员信息
	 */
	public LoginUser policeFingerprintLogin(String prisonId, String dormCode, byte[] fingerprint) {

		LoginUser loginUserDto = new LoginUser();
		Police police = null;
		try {
			police = fingerprintService.findPoliceByFingerprint(fingerprint, prisonId, dormCode);

		} catch (Exception ex) {
			log.error("登录失败", ex);
		}
		if (police != null) {
			loginUserDto.setUserType(LoginUser.USER_TYPE_POLICE);
			loginUserDto.setPolice(police);
		}

		return loginUserDto;
	}

	private void addPoliceIntoPrisonRecord(Police police, String jsh) {
		PoliceIntoPrisonRecord policeIntoPrisonRecord = new PoliceIntoPrisonRecord();
		String finalResultId =police.getPoliceId()+ convert2Id12(new Date());
		policeIntoPrisonRecord.setZybh(finalResultId);
		policeIntoPrisonRecord.setSksj(new Date());
		policeIntoPrisonRecord.setJsbh(jsbh);
		policeIntoPrisonRecord.setJsh(jsh);
		policeIntoPrisonRecord.setSklx((byte) 1);
		policeIntoPrisonRecord.setMjbh(police.getPoliceId());
		policeIntoPrisonRecord.setMjxm(police.getName());
		policeIntoPrisonRecord.setRfid(police.getCardId());
		policeIntoPrisonRecordRepository.save(policeIntoPrisonRecord);
	}

	public static String convert2Id12(Date date) {
		if (date == null) {
			return null;
		}
		return DateFormatUtils.format(date, "yyMMdd")
				+ String.format("%06x", nextInc.incrementAndGet() & 0x00FFFFFF);
	}
	private static AtomicInteger nextInc = new AtomicInteger((new java.util.Random()).nextInt());

}
